package top.codef.formatters;

import java.text.ParseException;
import java.util.Locale;

import javax.money.MonetaryAmount;
import javax.money.format.MonetaryFormats;

import org.apache.commons.lang3.StringUtils;
import org.springframework.format.Formatter;

import top.codef.money.interfaces.MercuryMonetaryAmountFormat;
import top.codef.properties.MercuryProperties;

public abstract class MoneyFormatter<T extends MonetaryAmount> implements Formatter<T> {

	protected final MercuryProperties mercuryProperties;

	private final Class<T> clazz;

	protected final MercuryMonetaryAmountFormat mercuryMonetaryAmountFormat;

	public MoneyFormatter(MercuryProperties mercuryProperties, Class<T> clazz,
			MercuryMonetaryAmountFormat mercuryMonetaryAmountFormat) {
		this.mercuryProperties = mercuryProperties;
		this.clazz = clazz;
		this.mercuryMonetaryAmountFormat = mercuryMonetaryAmountFormat;
	}

	public Class<T> targetClass() {
		return clazz;
	}

	@Override
	public String print(T object, Locale locale) {
		if (object != null) {
			String pr = MonetaryFormats.getAmountFormat(mercuryProperties.currentLocale()).format(object);
			return pr;
		}
		return null;
	}

	@Override
	public T parse(String text, Locale locale) throws ParseException {
		text = text.trim();
		if (StringUtils.isNoneBlank(text)) {
			T money = mercuryMonetaryAmountFormat.parse(text, clazz);
			return money;
		}
		return null;
	}

	public abstract T from(MonetaryAmount amount);
}
